<?php
namespace app\common\middleware;
use think\Facade\Db;

class CheckRule {
	public function handle($request, \Closure $next) {
		$group = \app\common\model\Group::find($request->user->user_id);
		$group->rules = explode(',', $group->rules);
		$request->group = $group;

		$response = $next($request);
		// 添加中间件执行代码
		$app = strtolower(app('http')->getName());
		$controller = $request->controller(true);
		$action = $request->action(true);
		//获取权限

		//判断是否有当前节点的访问权限
		if (!($app == 'index' && $controller == 'index')) {
			//站长权限
			if (!in_array(-1, $group->rules)) {
				$menus = Db::name('menu')->whereOr([
					[['app', '=', $app], ['controller', '=', $controller], ['action', '=', $action]],
					[['app', '=', $app], ['controller', '=', $controller], ['action', '=', '']],
					[['app', '=', $app], ['controller', '=', ''], ['action', '=', '']],
				])->select();
				if (count($menus) > 0) {
					$flag = false;
					foreach ($menus as $menu) {
						if (in_array($menu['menu_id'], $group->rules)) {
							$flag = true;
							break;
						}
					}
					if (!$flag) {
						return redirect('/Index/Index/Index');
					}
				}
			}
		}
		//dump($app);
		//dump($group->rules);
		return $response;
	}
}